package com.bw.module_motorcircle.ui.post

import androidx.lifecycle.MutableLiveData
import com.bw.lib_common.base.BaseViewModel
import com.bw.lib_common.base.state.RequestEvent
import com.bw.module_motorcircle.model.PostItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

/**
 * @author ytx
 * @date 2025-09-25 15:05
 * @description
 */
@HiltViewModel
class PostListViewModel @Inject constructor(private val repository: PostListRepository):BaseViewModel() {
    /**
     * 获得帖子数据
     * stateFlow:是一种特殊的sharedFlow,具有粘性 replay = 1，必须有初始值（sharedFlow默认0）
     */

    private val mPostState_ = MutableStateFlow<RequestEvent>(RequestEvent.Loading)
    val mPostState = mPostState_.asStateFlow()
    var mPostListData = listOf<PostItem>()

    val  mCheckIfHasFocus  by lazy{
        MutableLiveData<Boolean>()
    }

    //分页参数
    private var sortBy: String? = null
    private var keyword: String? = null
    private var memberId: String? = null
    private var ifFocus: Int? = null
    private var topicId : String? = null

     var pageNum = 1
     var pageSize = 4

    fun setPageParam(
        sortBy: String?,
        keyword: String?,
        memberId: String?,
        ifFocus: Int?,
        topicId: String?
    ) {
        this.sortBy = sortBy
        this.keyword = keyword
        this.memberId = memberId
        this.ifFocus = ifFocus
        this.topicId = topicId
    }
    /**
     *  检查是否关注
     */
    fun checkIfHasFocus(){
        execute(
            action =  repository.checkIfHasFocus(),
            onError = {
                mCheckIfHasFocus.value = false
            },
            onFinish = {
                mCheckIfHasFocus.value = it.data
            }
        )
    }
    /**
     * 帖子列表
     */
    fun pageList(){
        execute(
            action =  repository.pageList(sortBy, topicId, memberId, ifFocus, pageNum, pageSize, keyword),
            onStart = {
                mPostState_.value = RequestEvent.Loading
            },
            onFinish = {
                if(it.data.records.isNullOrEmpty()){//空数据
                    mPostState_.value = RequestEvent.Empty
                }else{
                    mPostListData = it.data.records!! //先数据后状态
                    mPostState_.value = RequestEvent.Success
                }
            },
            onError = {
                mPostState_.value = RequestEvent.Error(it)
            }
        )
    }

}